package com.xunsiya.service.system.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xunsiya.common.config.RequestUtils;
import com.xunsiya.common.config.util.*;
import com.xunsiya.module.order.dao.OrderDetailMapper;
import com.xunsiya.module.order.dao.OrderMapper;
import com.xunsiya.module.order.dao.ProductMapper;
import com.xunsiya.module.order.dao.ProductPriceMapper;
import com.xunsiya.module.order.vo.*;
import com.xunsiya.service.system.CompanyService;
import com.xunsiya.system.dao.AuthMapper;
import com.xunsiya.system.dao.CompanyMapper;
import com.xunsiya.system.dao.UserMapper;
import com.xunsiya.system.vo.Company;
import com.xunsiya.system.vo.User;
import com.xunsiya.tools.common.msg.Msg;
import com.xunsiya.tools.common.pagination.ForePage;
import com.xunsiya.tools.common.pagination.PagedUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


/**
 * @author fw
 *         群组管理
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class CompanyServiceImpl implements CompanyService {
    private static Logger logger = Logger.getLogger(CompanyServiceImpl.class);
    public static final String RETURNVALUE = "success";
    @Autowired
    private CompanyMapper companyMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AuthMapper authMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ProductPriceMapper productPriceMapper;
    /**
     * 紫万请求地址
     */
    @Value("${path.zwan-url}")
    private String zwUrl;
    /**
     * PAAS系统管理员登录账户
     */
    @Value("${path.zwan-name}")
    private String loginName;
    /**
     * PAAS系统管理员登录密码
     */
    @Value("${path.zwan-password}")
    private String loginPass;

    /**
     * 注册企业名称
     *
     * @param company
     * @return
     */
    @Override
    public int registerCompany(Company company) {
        int count = 0;
        //查询企业名称
        count = companyMapper.queryCompanyName(company.getCompanyName());
        if (count > 0) {
            return -1;
        }
        companyMapper.insertCompany(company);
        company.setResolution("480");
        company.setStatus(ConstantInfo.DelType.NORMAL.getType());
        companyMapper.insertVideoStreamCompany(company);
        return company.getId();
    }

    /**
     * 增加群组
     *
     * @param company
     * @return
     */
    @Override
    public Msg insertCompany(Company company) {
        int count = 0;
        //查询群组名称
        count = companyMapper.queryCompanyName(company.getCompanyName());
        if (count > 0) {
            return new Msg(false, "群组名称不能重复");
        }
        //查询联系Email
        count = companyMapper.queryCompanyEmail("%\"mail\":\"" + company.getEmail() + "\"%");
        if (count > 0) {
            return new Msg(false, "联系Email不能重复");
        }
        double remainderDuration = 0.0;
        /*if (company.getParentId() != 0) {
			Company cp = companyMapper.queryRemainderDuration(company.getParentId());
			remainderDuration = cp.getRemainderDuration() - company.getTotalDuration();
			if (remainderDuration < 0) {
				return new Msg(false, "总时长不能大于父群组的剩余时长！");
			}
		}*/
        User user = RequestUtils.getSessionAttribte(User.SYS_LOGIN_INFO);
        company.setAuthor(user.getId());
        companyMapper.insertCompany(company);
        company.setRemainderDuration(company.getTotalDuration());
        company.setStatus(ConstantInfo.DelType.NORMAL.getType());
        companyMapper.insertVideoStreamCompany(company);
        //修改父群组的剩余时长
        if (company.getParentId() != 0) {
            companyMapper.updateRemainderDuration(company.getParentId(), remainderDuration);
        }
        //插入订单表
        if (company.getParentId() == 0) {
            saveOrder(company, user);
        }
        return new Msg(true, "新增成功!", company);
    }

    @Override
    public void saveOrder(Company company, User user) {
        //订单详情
        List<ProductPrice> productList = productPriceMapper.queryAll();
        for (ProductPrice oneProduct : productList) {
            Order order = new Order();
            OrderDetail orderDetail = new OrderDetail();
            // 保存订单
            order.setOrderStatus(0);
            order.prePersist(user.getId() + "");
            order.setId(genId());
            order.setCompanyId(company.getId());
            // 人脸识别
            if (ConstantInfo.ProductType.FACE_REC.getValue() == oneProduct.getProductId()) {
                order.setImgUrl("0");
            }
            // 图像识别
            if (ConstantInfo.ProductType.IMG_REC.getValue() == oneProduct.getProductId()) {
                order.setImgUrl("1");
            }
            // 视频会议
            if (ConstantInfo.ProductType.TOPMETTING.getValue() == oneProduct.getProductId()) {
                order.setImgUrl("2");
            }
            orderMapper.save(order);
            //订单详情
            orderDetail.setProductId(oneProduct.getId().longValue());
            orderDetail.setProductService("3个月租借方案");
            orderDetail.setProductName(oneProduct.getProductName());
            // 保存订单详情
            orderDetail.setOrderId(order.getId());
            orderDetail.setId(genId());
            ZonedDateTime zonedDateTime = ZonedDateTime.now();
            ZonedDateTime outDate = zonedDateTime.plus(3, ChronoUnit.MONTHS);
            orderDetail.setOutDate(Date.from(outDate.toInstant()));
            orderDetail.prePersist(user.getId() + "");
            orderDetailMapper.save(orderDetail);
        }
    }

    /**
     * 生产id yyyyMMdd+时间戳+随机数（3）
     *
     * @return
     */
    private Long genId() {
        // 时间
        Date date = new Date();
        String dateStr = DateUtil.formatDate(date, "yyyy");
        // 随机数
        int random = (int) ((Math.random() + 1) * 10);
        return new Long(dateStr + date.getTime() + random);
    }

    /**
     * 查询群组
     *
     * @param companyId
     * @return
     */
    @Override
    public Msg queryCompany(int companyId) {
        List<Company> companyList = companyMapper.queryCompany(companyId);
        List<TreeNode<Company>> treeNodes = new ArrayList<>();
        for (Company cy : companyList) {
            TreeNode<Company> treeNode = new TreeNode<>();
            treeNode.setId(cy.getId().toString());
            treeNode.setParentId(cy.getParentId().toString());
            treeNode.setText(cy.getCompanyName());
            treeNode.setResolution(cy.getResolution());
            treeNode.setData(cy);
            treeNode.setSort(0);
            treeNodes.add(treeNode);
        }
        List<TreeNode> list = TreeUtil.build(treeNodes);
        return new Msg(true, "", list);
    }

    /**
     * 分页查询企业
     *
     * @param company
     * @return
     */
    @Override
    public Msg queryCompanyForPage(Company company, Integer pageIndex, Integer pageSize) {
        int count = companyMapper.queryCompanyCount(company);
        List<Company> companyList = companyMapper.queryCompanyForPage(company, PagedUtil.getStartIndex(pageIndex, pageSize), pageSize);
        //获取每页母公司的所有子公司
        List<Company> subCompanyList = new ArrayList<>();
        for (Company cp : companyList) {
            List<Company> oneSubList = companyMapper.queryCompany(cp.getId());
            if (oneSubList.size() > 1) {
                oneSubList.remove(oneSubList.size() - 1);
                for (Company cm : oneSubList) {
                    subCompanyList.add(cm);
                }
            }
        }
        List<Company> totalCompanyList = new ArrayList<>();
        totalCompanyList.addAll(companyList);
        totalCompanyList.addAll(subCompanyList);
        List<TreeNode<Company>> treeNodes = new ArrayList<>();
        for (Company cy : totalCompanyList) {
            TreeNode<Company> treeNode = new TreeNode<>();
            treeNode.setId(cy.getId().toString());
            treeNode.setParentId(cy.getParentId().toString());
            treeNode.setText(cy.getCompanyName());
            treeNode.setResolution(cy.getResolution());
            treeNode.setData(cy);
            treeNode.setSort(0);
            treeNodes.add(treeNode);
        }
        List<TreeNode> list = TreeUtil.build(treeNodes);
        return new Msg(true, "", new ForePage<>(count, pageIndex, list));
    }

    /**
     * 删除群组
     *
     * @param id
     * @return
     */
    @Override
    public Msg deleteCompany(int id) {
        Company company = companyMapper.queryCompanyById(id);
        if (companyMapper.querySubCompany(id) > 0) {
            return new Msg(false, "该群组下有子群组，不能删除!", company);
        }
        if (companyMapper.queryDevice(id) > 0) {
            return new Msg(false, "该群组下有设备，不能删除!", company);
        }
        if (companyMapper.queryUser(id) > 0) {
            return new Msg(false, "该群组下有用户，不能删除!", company);
        }
        if (company.getZwId() != null) {
            int companyId = company.getZwId();
            //请求紫万地址
            HashMap<String, Object> map = new HashMap<String, Object>(8);
            map.put("companyid", String.valueOf(companyId));
            StringBuffer sb = new StringBuffer();
            sb.append("companyid=").append(String.valueOf(companyId));
            sb = new StringBuffer(Md5Util.getMd5("MD5", 0, null, sb.toString()));
            sb.append(company.getZwPassword());
            String digest = Md5Util.getMd5("MD5", 0, null, sb.toString());
            map.put("digest", digest);
            String result = HttpClientUtil.getZwanPostResult(zwUrl + "zwgw/deletecompany", map);
            logger.info("result = " + result);
            JSONObject json = JSON.parseObject(result);
            if (RETURNVALUE.equals(json.getString("result"))) {
                Company pcompany = companyMapper.queryCompanyById(company.getParentId());
                if (null != pcompany) {
                    //删除子群组时，需要将子群组的总时长加回到父群主的剩余时长
                    pcompany.setRemainderDuration(company.getTotalDuration() + pcompany.getRemainderDuration());
                    companyMapper.updateCompany(pcompany);
                }
                //删除群组时，把t_videostream_company的status字段改为0
                companyMapper.updateVideoStreamCompany(id);
                //删除群组
                companyMapper.deleteCompany(id);
                return new Msg(true, "删除成功!", company);
            }
            return new Msg(false, "删除失败!", company);
        } else {
            Company pcompany = companyMapper.queryCompanyById(company.getParentId());
			/*if(null != pcompany)
			{
				//删除子群组时，需要将子群组的总时长加回到父群主的剩余时长
				pcompany.setRemainderDuration(company.getTotalDuration() + pcompany.getRemainderDuration());
				companyMapper.updateCompany(pcompany);
			}*/
            //删除群组时，把t_videostream_company的status字段改为0
            companyMapper.updateVideoStreamCompany(id);
            //删除群组
            companyMapper.deleteCompany(id);
            return new Msg(true, "删除成功!", company);
        }
    }

    /**
     * 修改群组
     *
     * @param company
     * @return
     */
    @Override
    public Msg modifyCompany(Company company) {
        Double sumDuration = companyMapper.querySumDuration(company.getId());
        if (null == sumDuration) {
            sumDuration = 0.0;
        }
        int pid = companyMapper.queryParentId(company.getId());
        Company cp = companyMapper.queryRemainderDuration(pid);
        Company scp = companyMapper.queryRemainderDuration(company.getId());
		/*if (cp != null) {
			if (company.getTotalDuration() <= cp.getTotalDuration()
					&& company.getTotalDuration() >= sumDuration) {
				double remainderDuration = 0.0;
				//修改上级群组的剩余时长
				if (company.getTotalDuration() > scp.getTotalDuration()) {
					remainderDuration = cp.getRemainderDuration() - (company.getTotalDuration() - scp.getTotalDuration());
				} else {
					remainderDuration = cp.getRemainderDuration() + (scp.getTotalDuration() - company.getTotalDuration());
				}
				if(remainderDuration >= 0)
				{
					companyMapper.updateRemainderDuration(pid, remainderDuration);
				}
				else
				{
					return new Msg(false, "总时长应小于父群组的总时长,大于子群组的总时长之和！");
				}
				//修改本级群组的剩余时长
				double sremainderDuration = 0.0;
				if (company.getTotalDuration() > scp.getTotalDuration()) {
					sremainderDuration = scp.getRemainderDuration() + (company.getTotalDuration() - scp.getTotalDuration());
				} else {
					sremainderDuration = scp.getRemainderDuration() - (scp.getTotalDuration() - company.getTotalDuration());
				}
				company.setRemainderDuration(sremainderDuration);
				companyMapper.updateCompany(company);
				companyMapper.updateVideostreamCompany(company);
				companyMapper.updateRemainderDuration(company.getId(), sremainderDuration);
			} else {
				return new Msg(false, "总时长应小于父群组的总时长,大于子群组的总时长之和！");
			}
		} else {
			//修改本级群组的剩余时长
			double sremainderDuration = 0.0;
			if (company.getTotalDuration() > scp.getTotalDuration()) {
				sremainderDuration = scp.getRemainderDuration() + (company.getTotalDuration() - scp.getTotalDuration());
			} else {
				sremainderDuration = scp.getRemainderDuration() - (scp.getTotalDuration() - company.getTotalDuration());
			}
			if(sremainderDuration >= 0)
			{
				company.setRemainderDuration(sremainderDuration);*/
        companyMapper.updateCompany(company);
        companyMapper.updateVideostreamCompany(company);
			/*	companyMapper.updateRemainderDuration(company.getId(), sremainderDuration);
			}
			else
			{
				return new Msg(false, "总时长应小于父群组的总时长,大于子群组的总时长之和！");
			}
		}*/
        return new Msg(true, "操作成功!");
    }

    /**
     * 查询所有群组
     *
     * @return
     */
    @Override
    public Msg queryAllCompany() {
        List<Company> companyList = companyMapper.queryAllCompany();
        List<TreeNode<Company>> treeNodes = new ArrayList<>();
        for (Company cy : companyList) {
            TreeNode<Company> treeNode = new TreeNode<>();
            treeNode.setId(cy.getId().toString());
            treeNode.setParentId(cy.getParentId().toString());
            treeNode.setText(cy.getCompanyName());
            treeNode.setResolution(cy.getResolution());
            treeNode.setData(cy);
            treeNode.setSort(0);
            treeNodes.add(treeNode);
        }
        List<TreeNode> list = TreeUtil.build(treeNodes);
        return new Msg(true, "", list);
    }

    /**
     * 查询本群组的所有下级
     *
     * @param companyId 用户所在群组id
     * @return
     */
    @Override
    public Msg getCompanyByUser(int companyId) {
        List<Company> companyList = companyMapper.getCompanyByUser(companyId);
//		companyList.remove(0);
        List<TreeNode<Company>> treeNodes = new ArrayList<>();
        for (Company cy : companyList) {
            TreeNode<Company> treeNode = new TreeNode<>();
            treeNode.setId(cy.getId().toString());
            treeNode.setParentId(cy.getParentId().toString());
            treeNode.setText(cy.getCompanyName());
            treeNode.setData(cy);
            treeNode.setSort(0);
            treeNodes.add(treeNode);
        }
        List<TreeNode> list = TreeUtil.build(treeNodes);
        return new Msg(true, "", list);
    }

    /**
     * 查询所有的公司
     *
     * @return
     */
    @Override
    public List<Company> findAll() {
        return companyMapper.queryAllCompany();
    }

    @Override
    public Company findParentId(int companyId) {
        return companyMapper.findParentId(companyId);
    }

    @Override
    public Company findCompanyByUser(String userName) {
        return companyMapper.findCompanyByUser(userName);
    }
}
